package com.spn.blog.api.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.spn.blog.api.config.RedisKey;
import com.spn.blog.api.service.ChatEndpoint;
import com.spn.blog.api.utils.MessageUtils;
import com.spn.blog.common.dao.pojo.LoginUser;
import com.spn.blog.common.dao.pojo.SysUser;
import com.spn.blog.common.utils.JWTUtils;
import com.spn.blog.common.utils.RedisCacheUtil;
import com.spn.blog.common.vo.Result;
import com.spn.blog.common.vo.UserVo;
import com.spn.blog.common.vo.params.LoginParam;
import com.spn.blog.service.login.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Api(tags = "系统模块")
@RestController
@RequestMapping("api/")
public class LoginController {

    @DubboReference(check = false)
    private LoginService loginService;
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private ChatEndpoint chatEndpoint;

    RedisCacheUtil redisCacheUtil = (RedisCacheUtil)RedisCacheUtil.getBean("redisCacheUtil");

    @ApiOperation(value = "用户登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginParam loginParam, HttpServletRequest request){
//        String ip = request.getRemoteAddr();
        String ip = request.getHeader("x-real-ip");
        loginParam.setLoginip(ip);
        Result result = loginService.login(loginParam);
        if(!result.isSuccess()) {
            return result;
        }
        String token = (String)result.getData();
        Map<String, Object> map = JWTUtils.checkToken(token);
        String userId = (String)map.get(JWTUtils.userKey);
        JSONObject jsonObject = redisCacheUtil.getCacheObject(RedisKey.USERINFO + userId);
        LoginUser loginUser = jsonObject.toJavaObject(LoginUser.class);
        SysUser sysUser = loginUser.getSysUser();
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(sysUser, userVo);
        chatEndpoint.sendAllMessage(MessageUtils.getMessage(true, "系统", userVo));
        return result;

    }

}
